//
//  InterstitialAdView.m
//  ebook
//
//  Created by 吴超飞 on 2016/11/21.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "InterstitialAdView.h"
#import "BaiduMobAdSDK/BaiduMobAdSplash.h"
#import "UIView+Extension.h"

//@import GoogleMobileAds;
//@class GADBannerView;

@interface InterstitialAdView()<BaiduMobAdInterstitialDelegate,SpotSDKDelegate>{//GADNativeExpressAdViewDelegate
    
    NSTimeInterval showTime;
    CGSize adsize;
    InterAdLocation adlocation;
    BOOL isShowAd;//标识当前是否显示广告
    InterstitialAdType adType;
    dispatch_source_t _googleLoadTimer;//google广告加载超时定时器
}

@property (nonatomic, retain) UIViewController *controller;
@property (nonatomic, retain) UIView *baiduAdView;
@property (nonatomic, retain) BaiduMobAdInterstitial *interstitialAdView;
//@property (nonatomic, retain) GADNativeExpressAdView *nativeExpressAdView;

@property (nonatomic, strong) NSMutableArray *alterlist;

@end

@implementation InterstitialAdView

-(void)showAdInController:(UIViewController *)controller size:(CGSize)size closeTime:(NSTimeInterval)time location:(InterAdLocation)location{
    
    showTime = time;
    adsize = size;
    adlocation = location;
    _controller = controller;
    
    NSString *key = @"";
    switch (location) {
        case InterAdInSpeek:
            key = @"speech";
            break;
        case InterAdInSearch:
            key = @"search_inter";
            break;
        default:
            break;
    }
    
    NSDictionary *dict = kBookCityDataDict;
    NSString *active = dict[@"ad"][key][@"active"];
    NSArray *alterlist = dict[@"ad"][key][@"alterlist"];
    _alterlist = [NSMutableArray arrayWithArray:alterlist];
    
    [self loadSplashAd:active];
}

//根据类型加载对应的广告
-(void)loadSplashAd:(NSString *)active{
    
//    active = @"baidu";//测试
    if([active isEqualToString:@"baidu"]){//显示百度广告
        [self loadBaiduInterstitialAd];
    }else if([active isEqualToString:@"google"]){
//        [self loadGoogleNativeExpressAdView];
    }else if([active isEqualToString:@"tanv"]){
        [self loadTanvSpotAd];
    }
}

//一种广告失败后，加载另一种备选广告
-(void)loadNextSpotAd{
    
    if(_alterlist.count>0){
        NSString *next = _alterlist.firstObject;
        [self loadSplashAd:next];
        [_alterlist removeObjectAtIndex:0];
    }
}

//广告右上角添加干扰关闭按钮  该功能不再使用
-(void)addTroubleOnView:(UIView *)adView{
    
    if(adlocation != InterAdInSearch && adType != InterstitialAdGoogle)//只有搜索界面的google插屏广告加关闭按钮
        return;
    float x = MTScreenW - 30;
    float y = 0;
    UIImage *image = [UIImage imageNamed:@"delete2"];
    
    CGRect frame = CGRectMake(x, y, 30, 30);
    UIButton *coverBtn = [[UIButton alloc]initWithFrame:frame];
    
    coverBtn.layer.cornerRadius = 5.0f;
    coverBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [coverBtn setBackgroundImage:image forState:UIControlStateNormal];
    [coverBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    [adView addSubview:coverBtn];
}

//是否点透
-(BOOL)isResponseCloseClick{
    
    int x = arc4random() % 100;
    NSDictionary *dict = kBookCityDataDict;
    int rate = [dict[@"jumprate"] intValue];
    
    return x<rate;
}

-(void)dismiss{
    
    if(_interstitialAdView){
        _interstitialAdView.delegate = nil;
        _interstitialAdView = nil;
    }
    if (_baiduAdView) {
        [_baiduAdView removeFromSuperview];
    }
//    if (_nativeExpressAdView) {
//        [_nativeExpressAdView removeFromSuperview];
//    }
    isShowAd = NO;
}

-(void)cancel{
    
    isShowAd = YES;
}

-(void)loadBaiduInterstitialAd{
    
    adType = InterstitialAdBaidu;
    self.interstitialAdView = [[BaiduMobAdInterstitial alloc]init];
    NSDictionary *dict = kBookCityDataDict;
    NSString *adunit = nil;
    switch (adlocation) {
        case InterAdInSpeek:{
            NSString *serverAdUnitTag = dict[@"ad"][@"speech"][@"baidu"][@"AdUnitTag"];
            adunit = serverAdUnitTag.length>0?serverAdUnitTag:kBaiduMobSpeekInterstitialAdUnitTag;
        }
            break;
        case InterAdInSearch:{
            NSString *serverAdUnitTag = dict[@"ad"][@"search_inter"][@"baidu"][@"AdUnitTag"];
            adunit = serverAdUnitTag.length>0?serverAdUnitTag:kBaiduMobSearchInterstitialAdUnitTag;
        }
            break;
        default:
            break;
    }
    self.interstitialAdView.AdUnitTag = adunit;
    self.interstitialAdView.delegate = self;
    self.interstitialAdView.interstitialType = BaiduMobAdViewTypeInterstitialPauseVideo;
    CGRect rect = adlocation==InterAdInSearch?CGRectMake(0, 0, MTScreenW, 0.75*MTScreenW):CGRectMake(0, 0, kAdWidth, kAdHeight);
    [self.interstitialAdView loadUsingSize:rect];
}

-(void)showBaiduInterstitial{
    
    if (self.interstitialAdView.isReady) {
        
        if(isShowAd)return;
        isShowAd = YES;
        if (adlocation == InterAdInSpeek) {
            
            [self.interstitialAdView presentFromView:self.controller.view];
        }else{
            
            CGRect rect = adlocation==InterAdInSearch?CGRectMake(0, 0, MTScreenW, 0.75*MTScreenW):CGRectMake(0, 0, kAdWidth, kAdHeight);
            self.baiduAdView.frame = rect;
            self.baiduAdView.center = self.controller.view.center;
            [self.controller.view addSubview:self.baiduAdView];
            [self.interstitialAdView presentFromView:self.baiduAdView];
            self.baiduAdView.centerY = self.baiduAdView.height/2-10;//-20隐藏上面的白边
            self.baiduAdView.centerX = self.controller.view.centerX;
        }
        
        if(showTime>0){
            __weak typeof(self) weakSelf = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(showTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//倒计时移除视图
                __strong typeof(self) strongSelf = weakSelf;
                [strongSelf dismiss];
                isShowAd = NO;
            });
        }
    }
}

-(UIView *)baiduAdView{
    
    if (!_baiduAdView) {
        UIView *baiduAdView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kAdWidth, kAdHeight)];
        baiduAdView.backgroundColor = [UIColor clearColor];
        _baiduAdView = baiduAdView;
    }
    return _baiduAdView;
}

#pragma mark - BaiduMobAdInterstitialDelegate
- (BOOL) enableLocation {
    return NO;
}

- (NSString *)publisherId {
    
    NSDictionary *dict = kBookCityDataDict;
    NSString *node = @"";
    switch (adlocation) {
        case InterAdInSpeek:{
            node = @"speech";
        }
            break;
        case InterAdInSearch:{
            node = @"search_inter";
        }
            break;
        default:
            break;
    }

    NSString *serverBaiduadid = dict[@"ad"][node][@"baidu"][@"AppId"];
    
    return serverBaiduadid.length>0?serverBaiduadid:kBaiduMobAdPublisherId;
}

/*
 *  广告预加载成功
 */
- (void)interstitialSuccessToLoadAd:(BaiduMobAdInterstitial *)interstitial {
    
    MTLog(@"插屏广告预加载成功");
    [[BaiduMobStat defaultStat] logEvent:@"BInterstitialSuccess" eventLabel:interstitial.AdUnitTag];
    [self showBaiduInterstitial];
}

/**
 *  广告展示结束
 */
- (void)interstitialDidDismissScreen:(BaiduMobAdInterstitial *)interstitial{
    
    MTLog(@"插屏广告消失");
    [self.baiduAdView removeFromSuperview];
    _interstitialAdView = nil;
    isShowAd = NO;
}

/**
 *  广告预加载失败
 */
- (void)interstitialFailToLoadAd:(BaiduMobAdInterstitial *)interstitial {
    MTLog(@"插屏广告加载失败");
    NSString *event;
    switch (adlocation) {
        case InterAdInSpeek:
            event = @"BInterFailToLoadAd1";
            break;
        case InterAdInSearch:
            event = @"BInterFailToLoadAd2";
            break;
        default:
            break;
    }
    [[BaiduMobStat defaultStat] logEvent:event eventLabel:interstitial.AdUnitTag];
    [self loadNextSpotAd];
}

/**
 *  广告即将展示
 */
- (void)interstitialWillPresentScreen:(BaiduMobAdInterstitial *)interstitial {
    MTLog(@"插屏广告即将展示");
}

/**
 *  广告展示成功
 */
- (void)interstitialSuccessPresentScreen:(BaiduMobAdInterstitial *)interstitial {
    MTLog(@"插屏广告展示成功");
    NSString *event;
    switch (adlocation) {
        case InterAdInSpeek:
            event = @"BInterSuccessPresent1";
            break;
        case InterAdInSearch:
            event = @"BInterSuccessPresent2";
            break;
        default:
            break;
    }
    [[BaiduMobStat defaultStat] logEvent:event eventLabel:interstitial.AdUnitTag];
}

/**
 *  广告展示失败
 */
- (void)interstitialFailPresentScreen:(BaiduMobAdInterstitial *)interstitial withError:(BaiduMobFailReason) reason {
    MTLog(@"插屏广告展示失败 %d", reason);
    NSString *event;
    switch (adlocation) {
        case InterAdInSpeek:
            event = @"BInterFailPresentScreen1";
            break;
        case InterAdInSearch:
            event = @"BInterFailPresentScreen2";
            break;
        default:
            break;
    }
    [[BaiduMobStat defaultStat] logEvent:event eventLabel:interstitial.AdUnitTag];
}

/**
 *  广告展示被用户点击时的回调
 */
- (void)interstitialDidAdClicked:(BaiduMobAdInterstitial *)interstitial {
    MTLog(@"插屏广告用户点击");
    NSString *event;
    switch (adlocation) {
        case InterAdInSpeek:
            event = @"BInterDidAdClicked1";
            break;
        case InterAdInSearch:
            event = @"BInterDidAdClicked2";
            break;
        default:
            break;
    }
    [[BaiduMobStat defaultStat] logEvent:event eventLabel:interstitial.AdUnitTag];
}

/**
 *  广告详情页被关闭
 */
- (void)interstitialDidDismissLandingPage:(BaiduMobAdInterstitial *)interstitial {
    MTLog(@"插屏广告详情页被关闭");
}

- (void)dealloc {
    
    [self dismiss];
}
/*
#pragma mark - Google Ad

-(void)loadGoogleNativeExpressAdView{
    
    adType = InterstitialAdGoogle;
    GADNativeExpressAdView *nativeExpressAdView = [[GADNativeExpressAdView alloc]initWithAdSize:adlocation==InterAdInSearch?GADAdSizeFromCGSize(CGSizeMake(MTScreenW, MTScreenW*5/6)):kGADAdSizeMediumRectangle];//300x250.  kGADAdSizeMediumRectangle
    NSString *adunit = nil;
    switch (adlocation) {
        case InterAdInSpeek:
            adunit = kGoogleAdMobSpeekNativeCenterUnit;
            break;
        case InterAdInSearch:
            adunit = kGoogleAdMobSearchNativeCenterUnit;
            break;
        default:
            break;
    }
    nativeExpressAdView.adUnitID = adunit;
    nativeExpressAdView.rootViewController = _controller;
    nativeExpressAdView.delegate = self;
    self.nativeExpressAdView = nativeExpressAdView;
    
    GADRequest *request = [GADRequest request];
    request.testDevices = @[@"a7ea75dd6c64ce1b4e176e5ba623d7a8",@"6e40b39f9159f6d3ac5b20c75aa3331a",@"61316d31021622f915cb9a6c011627f6"];
    [self.nativeExpressAdView loadRequest:request];
    [self loadGoogleAdTimer];
}

-(void)loadGoogleAdTimer{
    
    __block int timeout = 10;
    dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    _googleLoadTimer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
    dispatch_source_set_timer(_googleLoadTimer,dispatch_walltime(NULL,0),1.0 * NSEC_PER_SEC,0);
    dispatch_source_set_event_handler(_googleLoadTimer, ^{
        if(timeout <=0){
            //取消
            dispatch_source_cancel(_googleLoadTimer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self loadNextSpotAd];
            });
            
        }else{
            
            timeout--;
        }
        MTLog(@"google插屏加载倒计时:%d",timeout);
    });
    //启动
    dispatch_resume(_googleLoadTimer);
}

-(void)showGoogleNativeExpressAdView{
    
    if(isShowAd)return;
    isShowAd = YES;
    [_controller.view addSubview:self.nativeExpressAdView];
    [_controller.view bringSubviewToFront:self.nativeExpressAdView];
    self.nativeExpressAdView.center = self.controller.view.center;
    if(adlocation == InterAdInSearch){
        self.nativeExpressAdView.centerY = self.nativeExpressAdView.height/2;
        self.nativeExpressAdView.centerX = self.controller.view.centerX;
    }
    [self addTroubleOnView:self.nativeExpressAdView];
    
    if(showTime>0){
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(showTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//倒计时移除视图
            __strong typeof(self) strongSelf = weakSelf;
            [strongSelf.nativeExpressAdView removeFromSuperview];
            isShowAd = NO;
        });
    }
}

- (void)nativeExpressAdViewDidReceiveAd:(GADNativeExpressAdView *)nativeExpressAdView{
    
    dispatch_source_cancel(_googleLoadTimer);
    MTLog(@"google原生广告加载成功");
    [self showGoogleNativeExpressAdView];
    NSString *event;
    switch (adlocation) {
        case InterAdInSpeek:
            event = @"GoogleInterAdDidReceive1";
            break;
        case InterAdInSearch:
            event = @"GoogleInterAdDidReceive2";
            break;
        default:
            break;
    }
    [[BaiduMobStat defaultStat] logEvent:event eventLabel:nativeExpressAdView.adUnitID];
}

- (void)nativeExpressAdView:(GADNativeExpressAdView *)nativeExpressAdView
didFailToReceiveAdWithError:(GADRequestError *)error{
    
    dispatch_source_cancel(_googleLoadTimer);
    MTLog(@"google原生（插屏）广告加载失败 error：%@",error);
    [self loadNextSpotAd];//加载失败则显示备选广告
    NSString *event;
    switch (adlocation) {
        case InterAdInSpeek:
            event = @"GoogleInterAdFailToReceiveAd1";
            break;
        case InterAdInSearch:
            event = @"GoogleInterAdFailToReceiveAd2";
            break;
        default:
            break;
    }
    [[BaiduMobStat defaultStat] logEvent:event eventLabel:nativeExpressAdView.adUnitID];
}

- (void)nativeExpressAdViewWillLeaveApplication:(GADNativeExpressAdView *)nativeExpressAdView{
    MTLog(@"google原生（插屏）广告点击");
    NSString *event;
    switch (adlocation) {
        case InterAdInSpeek:
            event = @"GoogleInterLeaveApplication1";
            break;
        case InterAdInSearch:
            event = @"GoogleInterLeaveApplication2";
            break;
        default:
            break;
    }
    [[BaiduMobStat defaultStat] logEvent:event eventLabel:nativeExpressAdView.adUnitID];
}
*/
#pragma mark - 巨鲨插屏

-(void)loadTanvSpotAd{

    if(isShowAd)return;
    isShowAd = YES;
    SpotSDK *spotSDK = [[SpotSDK alloc]initWithUserId:kTanvUserid appId:kTanvAppid appKey:kTanvAppkey];
    spotSDK.delegate = self;
    [spotSDK loadSpot];
}

-(void)closeSpot:(SpotSDK *)spotSDK{
   
    [[BaiduMobStat defaultStat] logEvent:@"TanvSpotClose" eventLabel:@"close"];
    isShowAd = NO;
}

-(void)clickSpot:(SpotSDK *)spotSDK{
   
    [[BaiduMobStat defaultStat] logEvent:@"TanvSpotClick" eventLabel:@"click"];
}

-(void)successToFetchSpot:(SpotSDK *)spotSDK{
    
    [[BaiduMobStat defaultStat] logEvent:@"TanvSpotSuccessToFetch" eventLabel:@"success"];
    //加载成功，显示插屏
//    [spotSDK showSpot:[UIApplication sharedApplication].keyWindow];
    [spotSDK showSpotWithViewController:_controller];
}

-(void)failToFetchSpot:(SpotSDK *)spotSDK error:(NSError *)error{
    
    [[BaiduMobStat defaultStat] logEvent:@"TanvSpotFailToFetch" eventLabel:@"fail"];
    [self loadNextSpotAd];//加载失败则显示备选广告
}

@end
